package logic

import (
	"context"
	"fmt"
	"housing/model/redis"
	"math/rand"
	"time"

	"housing/housingrpc/housingrpc"
	"housing/housingrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *housingrpc.SendSmsRequest) (*housingrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	hour, _ := redis.Client.Get("sendSmsHour" + in.Phone).Int()

	if hour >= 10 {
		return nil, fmt.Errorf("2小时内只能发送十次")
	}

	/*five := redis.Client.Get("sendSmsFive" + in.Phone)

	if five.Val() >= "1" {
		return nil, fmt.Errorf("五分钟内只能发送一次")
	}
	*/
	code := rand.Intn(9000) + 1000

	//
	//sms, err := pkg.SendSms(in.Account, strconv.Itoa(code))
	//if err != nil {
	//	return nil, err
	//}
	//
	//if *sms.Body.Code != "OK" {
	//	return nil, fmt.Errorf(*sms.Body.Message)
	//}

	redis.Client.Set("sendSms"+in.Source+in.Phone, code, time.Minute*5)

	//5分钟只能发送1次
	/*fiveIncr := redis.Client.Incr("sendSmsFive" + in.Phone)

	if fiveIncr.Val() == 1 {
		redis.Client.Expire("sendSmsFive"+in.Phone, time.Minute*5)
	}*/
	//2小时内发送十次
	incr := redis.Client.Incr("sendSmsHour" + in.Phone)

	if incr.Val() == 1 {
		redis.Client.Expire("sendSmsHour"+in.Phone, time.Hour*2)
	}
	return &housingrpc.SendSmsResponse{}, nil
}
